package com.noahplat.alarm.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.alarm.mapper.AlarmMapper;
import com.noahplat.alarm.pojo.Alarm;
import com.noahplat.alarm.service.AlarmService;
import com.noahplat.common.utils.*;
import com.noahplat.person.feign.PersonDeviceFeign;
import com.noahplat.person.feign.PersonFeign;
import com.noahplat.person.feign.PersonInfoFeign;
import com.noahplat.person.pojo.Person;
import com.noahplat.person.pojo.PersonDevice;
import com.noahplat.person.pojo.PersonInfo;
import com.noahplat.user.feign.UserFeign;
import com.noahplat.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class AlarmServiceImpl implements AlarmService {
    @Autowired
    private AlarmMapper alarmMapper;
    @Autowired
    private JpushUtils jpushUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private PersonFeign personFeign;
    @Autowired
    private PersonInfoFeign personInfoFeign;
    @Autowired
    private PersonDeviceFeign personDeviceFeign;
    @Autowired
    private UserFeign userFeign;

    public static final String TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6ImFkbWluIiwiYWNjdGlkIjoxLCJzdGlkIjoiMiIsInBpZCI6MSwiaWQiOjYsInVzZXJUeXBlIjoiMCIsImV4cCI6MTcxNjg3NDUwMCwiYXV0aG9yaXRpZXMiOlsibm9haHBsYXQtc2VydmljZS1wZXJzb246UGVyc29uQ29udHJvbGxlcjpnZXRVaWQiXSwianRpIjoiMzk3OWQ1ZjgtOGRmNC00MzIyLTgzYjYtZmJhMzI0NDgxNjdiIiwiY2xpZW50X2lkIjoibm9haHBsYXQiLCJ1c2VybmFtZSI6ImFkbWluIn0.aZ23Ad6Rm59pP69zy8KukF28tMeYN8U3cY5XG03d8Gg-40JmWx6eqWyOb7gYxiXK6y_XU9wP1LOEPPT7G6i4u2ZLg9OtmlNi781I8bhkairJKveeOLWoN5Y99UVnSJfOHZMnMy5O3kFk1fjTe--RlRZJtkFIsByyqIVVNCy_5jy-uuYT_6CN9f27pCzW6vgbNKTrwhKhi_7oHDe3k3Kl6aNl85WIZOde73BbQoChuBQvz1y4UqVcjVTAtugzlTw3TdE7c78iInZW5xMUpjeme1Gt2Z9R11lnT_jKNdXJ4uhjIwRIU667L91SALktrBFxMGLRez8rUDf9_CexqJlKiA";

    public static final String REDISTOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6ImFkbWluIiwiYWNjdGlkIjoxLCJzdGlkIjoiMiIsInBpZCI6MSwiaWQiOjYsInVzZXJUeXBlIjoiMCIsImV4cCI6MTcxNjg3NDQzMSwiYXV0aG9yaXRpZXMiOlsibm9haHBsYXQtc2VydmljZS1wZXJzb246UGVyc29uRGV2aWNlQ29udHJvbGxlcjppblJlZGlzIl0sImp0aSI6ImRhZjhhZjBjLTNhY2YtNDQyNy1iNzhlLWE1MWUxZGQ2MjdkYiIsImNsaWVudF9pZCI6Im5vYWhwbGF0IiwidXNlcm5hbWUiOiJhZG1pbiJ9.NpgWJQuC9Ia_-lkMRZ8SKloZ0rWWW9PPFnYUxTaNOEbUr7wUI_3wZvrc7-7W1lF49G4G0Ot_aHHauH5af4ro3RkuYplhHJ0_WHYWPzxSa60gpi0vm-GvLl8RioZYcCp_31eAHkq549dceVNVpt1OY8A2CoTyS8Ua4wSDraoujb_G3mSvdzOp4Ba1SAWYgWpGKsNHFkOfTBn5YJru6TJAF2DgAX0PjbyG4WNk0OFe6AqJpiZdU_zEIPNFaUell677ccaTHQwBtKP179_JdZJtsx2OU-3K1z0Pz7X-D1tzsj9dyW_-nsF0MFSNFL2Q3zFkUyE07FqpJuvGajlSmUMtqw";


    /**
     * 登记报警信息接口
     *
     * @return
     */
    @Override
    public void addAlarm(Alarm alarm) {
        boolean keyres = redisUtils.hasKey(NoahEnum.JPUSHDIR.getCode()+alarm.getImei());
        if(!keyres){
            Result result = personDeviceFeign.inRedis(alarm.getImei(),"Bearer " +REDISTOKEN);
            if(!result.isFlag()){
                return;
            }
        }
        List<Object> list = redisUtils.lGet(NoahEnum.JPUSHDIR.getCode() + alarm.getImei(), 0, -1);
        if (ObjectUtils.isEmpty(list)) {
            return;
        }
        Set<Long> pidset = new HashSet<>();
        for (Object object : list) {
            PersonDevice personDevice = (PersonDevice) object;
            pidset.add(personDevice.getPid());
            Map<String, String> map = new HashMap<>();
            map.put("title", alarm.getAlarm());
            map.put("id", personDevice.getRegistrationid());
            map.put("type",alarm.getType());
            map.put("msg", alarm.getAlarm());
            jpushUtils.jpushAll(map);
        }
        Long[] pid = pidset.toArray(new Long[pidset.size()]);
        Result<List<Person>> result = personFeign.getUid(pid, "Bearer " + TOKEN);
        if (!result.isFlag()) {
            return;
        }
        List<Person> list1 = result.getData();
        int res = alarmMapper.insertAlarm(list1, alarm.getImei(), alarm.getAlarm(),alarm.getType(),"", "0", new Date());
        if (res == 0) {
            return;
        }
        return;
    }

    /**
     * 通过uid查询报警信息
     *
     * @param page
     * @param limit
     * @param uid
     * @return
     */
    @Override
    public Result getAlarm(Integer page, Integer limit, Long uid) {
        PageHelper.startPage(page, limit);
        Example example = new Example(Alarm.class);
        example.createCriteria().orEqualTo("uid", uid);
        example.setOrderByClause("id desc");
        List<Alarm> list = alarmMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "无警报信息");
        }
        PageInfo<Alarm> pageInfo = new PageInfo<>(list);
        return new Result(true, StatusCode.OK, "查询报警信息成功", pageInfo);
    }

    /**
     * 条件查询报警信息接口
     *
     * @param page
     * @param limit
     * @param state
     * @param startdate
     * @param enddate
     * @return
     */
    @Override
    public Result getAlarms(Integer page, Integer limit, Long acctid, String state, String startdate, String enddate) {
        Date statetime = null;
        Date endtime = null;
        PageHelper.startPage(page, limit);
        if (!StringUtils.isEmpty(startdate) && !StringUtils.isEmpty(enddate)) {
            try {
                statetime = dateUtil.stringToDate(startdate, dateUtil.PATTERN_YYYY_MM_DD);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,StatusCode.ERROR,"日期格式异常");
            }
            Date end = null;
            try {
                end = dateUtil.stringToDate(enddate, dateUtil.PATTERN_YYYY_MM_DD);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,StatusCode.ERROR,"日期格式异常");
            }
            endtime = dateUtil.addDateDay(end, 1);
        }

        Example example = new Example(Alarm.class);
        example.createCriteria().andEqualTo("acctid", acctid);
        if (!StringUtils.isEmpty(state)) {
            example.and(example.createCriteria().andEqualTo("state", state));
        }
        example.and(example.createCriteria().andGreaterThanOrEqualTo("addtime", statetime).andLessThan("addtime", endtime));
        example.setOrderByClause("id desc");
        List<Alarm> list = alarmMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "无警报信息");
        }
        PageInfo<Alarm> pageInfo = new PageInfo<>(list);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /**
     * 根据id查询报警信息
     *
     * @param id
     * @return
     */
    @Override
    public Result getAlarmById(Long id) {
        Example example = new Example(Alarm.class);
        example.createCriteria().orEqualTo("id", id);
        Alarm alarm = alarmMapper.selectOneByExample(example);
        if (ObjectUtils.isEmpty(alarm)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "无此报警信息");
        }
        Result result = personInfoFeign.getPersonInfo(alarm.getPid());
        Map map = (Map) result.getData();
        if (ObjectUtils.isEmpty(map)) {
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
        alarm.setName(map.get("name").toString());
        return new Result(true, StatusCode.OK, "查询成功", alarm);
    }

    /**
     * 修改报警信息
     *
     * @param alarm
     * @return
     */
    @Override
    public Result updateAlarm(Alarm alarm){
        Result<User> result = userFeign.findUserById(alarm.getPayuid());
        if(!result.isFlag()){
            return new Result(false,StatusCode.ERROR,"获取操作人失败");
        }
        User user = result.getData();
        alarm.setUser(user.getName());
        int res = alarmMapper.updateByPrimaryKeySelective(alarm);
        if (res == 0) {
            return new Result(false, StatusCode.ERROR, "修改报警信息失败");
        }
        return new Result(true, StatusCode.OK, "修改报警信息成功");
    }

}
